In this C++ tutorial, we are going to cover the topic comments. Here we will define what are comments in C++ and why we use them, with the help of some examples.
C++ Comments
Comments are those statements that do not compile by the C++ compiler when a C++ compiler try to compile the program from top to bottom if there is any statement which starts with // or /* symbol C++ just ignore that statement and move to the next line.
Why we use Comments in C++?
In every programming language we have some special symbols to represent the comments, comments are the simple messages or details used to provide the information about the written code, so if some other developer read your code he could get what this code supposed to do.
Types of Comments
In C++ we have two types of comments:
- Single line comments (//)
- Multi-lines Comments (start with /* and end with */)
1. Single-Line Comments
To represent a single line comment, we use two forward slash symbols “//”, this is called single line comment because with this symbol we are only able to comment a single line. Example:
10 + 20; // this statement will add 10 and 20 30 – 20; // this statement will subtract 20 from 30
2. Multi-Line Comments
As its name suggests in multi-line comments we can comment out multiple lines. To comment out multiple lines, we start which /* symbol and to end the comment flow we stop it with */ symbol. Example:
/* cout<< 10+20; the above statement won’t be compiled by the C++ compiler, because it resides in multi-line comment */
Proper example to represent the Single as well as multi-line comments:
#include <iostream> using namespace std; /* this program has two cout statements, but only one will execute,because other is commented */ int main() { // cout << "Hello World"; cout<<"Comment Example"; //Only this cout statement will be executed return 0; }
Output:
Comment Example
Note: The above example has been compiled and executed in Dev C++ Ide, if you are using Turbo C++ IDE there you need to specify all the header files, so we suggest you, use Dev C++ for this tutorial session. Quick Summary:
- Comments are used to provide information about the code.
- If we comment any statement compiler won’t compile it
- There are two types of Comments in C++ Single line comments and multi-line comments
- To represent single-line comment, we use // symbol
- The multi-line comment starts with /* and ends with */.
People are also reading:
- Function Call Operator() Overloading in C++
- C++ Basic Syntax
- Assignment Operators Overloading in C++
- Input/Output Operators Overloading in C++
- C++ Environment Setup
- Relational Operators Overloading in C++
- Object Oriented Programming
- Binary Operators Overloading in C++
- Unary Operators Overloading in C++